package org.jsola.hr.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.jsola.core.Page;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ISalaryBasicDAO;
import org.jsola.hr.dao.ISalaryChangesDAO;
import org.jsola.hr.dto.SalaryBasicAddDTO;
import org.jsola.hr.dto.SalaryBasicUpdateDTO;
import org.jsola.hr.entity.SalaryBasicDO;
import org.jsola.hr.entity.SalaryChangesDO;
import org.jsola.hr.query.SalaryBasicQuery;
import org.jsola.hr.query.SalaryChangesQuery;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.hr.service.ISalaryBasicService;
import org.jsola.hr.vo.SalaryBasicListVO;
import org.jsola.hr.vo.SalaryBasicVO;
import org.jsola.hr.vo.SalaryChangesVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 员工薪资表
 *
 * @author zhr
 */
@Service("hrSalaryBasicServiceImpl")
public class SalaryBasicServiceImpl implements ISalaryBasicService {

    @Autowired
    private ISalaryBasicDAO salaryBasicDAO;
    @Autowired
    private ISalaryChangesDAO salaryChangesDAO;
    @Autowired
    private IEmpInfoService empInfoService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SalaryBasicVO save(SalaryBasicAddDTO salaryBasicAddDTO, TokenUser tokenUser) {
        // 转DO
        SalaryBasicDO salaryBasicDO = salaryBasicAddDTO.to(SalaryBasicDO.class);
        // 保存
        salaryBasicDO = save(salaryBasicDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return salaryBasicDO.to(SalaryBasicVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(SalaryBasicUpdateDTO salaryBasicUpdateDTO, TokenUser tokenUser) {
        //转DO
        SalaryBasicDO salaryBasicDO = salaryBasicUpdateDTO.to(SalaryBasicDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(salaryBasicDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... salaryBasicIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) salaryBasicIds);
    }


    @Override
    public SalaryBasicVO selectById(String salaryBasicId, String siteId) {
        SalaryBasicDO salaryBasicDO = selectDOById(salaryBasicId, siteId);
        if (salaryBasicDO == null) {
            return null;
        }
        return salaryBasicDO.to(SalaryBasicVO.class);
    }

    @Override
    public List<SalaryBasicListVO> select(SalaryBasicQuery salaryBasicQuery, String siteId) {
        List<SalaryBasicDO> salaryBasicDOList = selectDO(salaryBasicQuery, siteId);
        if (CollectionUtils.isEmpty(salaryBasicDOList)) {
            return salaryBasicDOList == null ? null : new ArrayList<>();
        }
        return salaryBasicDOList.stream()
                .map(salaryBasicDO -> salaryBasicDO.to(SalaryBasicListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(SalaryBasicQuery salaryBasicQuery, String siteId) {
        Example example = buildExample(salaryBasicQuery, siteId);
        return salaryBasicDAO.selectCountByExample(example);
    }

    @Override
    public Page<SalaryBasicListVO> selectPage(SalaryBasicQuery salaryBasicQuery, String siteId) {
        Example example = buildExample(salaryBasicQuery, siteId);
        Page<SalaryBasicDO> page = salaryBasicDAO.selectPageByExample(example,
                salaryBasicQuery.getPageNo(),
                salaryBasicQuery.getPageSize());

        return page.to(SalaryBasicListVO.class);
    }

    @Override
    public SalaryBasicDO selectDOById(String salaryBasicId, String siteId) {
        return listById(salaryBasicId, siteId);
    }

    @Override
    public List<SalaryBasicDO> selectDO(SalaryBasicQuery salaryBasicQuery, String siteId) {
        Example example = buildExample(salaryBasicQuery, siteId);
        return salaryBasicDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example
     *
     * @param salaryBasicQuery 查询参数
     * @param siteId           所属站点id
     * @return example
     */
    private Example buildExample(SalaryBasicQuery salaryBasicQuery, String siteId) {
        Example example = new Example(SalaryBasicDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (salaryBasicQuery.getEmpId() != null) {
            example.and().andLike("empId", "%" + salaryBasicQuery.getEmpId() + "%");
        }
        if (salaryBasicQuery.getSalaryBasic() != null) {
            example.and().andEqualTo("salaryBasic", salaryBasicQuery.getSalaryBasic());
        }
        if (salaryBasicQuery.getTrafficSubsidy() != null) {
            example.and().andEqualTo("trafficSubsidy", salaryBasicQuery.getTrafficSubsidy());
        }
        if (salaryBasicQuery.getMealSubsidy() != null) {
            example.and().andEqualTo("mealSubsidy", salaryBasicQuery.getMealSubsidy());
        }
        if (salaryBasicQuery.getSalaryPerformance() != null) {
            example.and().andEqualTo("salaryPerformance", salaryBasicQuery.getSalaryPerformance());
        }
        if (salaryBasicQuery.getReason() != null) {
            example.and().andEqualTo("reason", salaryBasicQuery.getReason());
        }
        if (salaryBasicQuery.getRemark() != null) {
            example.and().andEqualTo("remark", salaryBasicQuery.getRemark());
        }
        if (salaryBasicQuery.getSalaryTotal() != null) {
            example.and().andEqualTo("salaryTotal", salaryBasicQuery.getSalaryTotal());
        }
        if (salaryBasicQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", salaryBasicQuery.getCompanyId());
        }
        if (salaryBasicQuery.getGmtCreateStart() != null &&
                salaryBasicQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", salaryBasicQuery.getGmtCreateStart(),
                    salaryBasicQuery.getGmtCreateEnd());
        }
        if (salaryBasicQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + salaryBasicQuery.getCreateUserId() + "%");
        }
        if (salaryBasicQuery.getGmtModifiedStart() != null &&
                salaryBasicQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", salaryBasicQuery.getGmtModifiedStart(),
                    salaryBasicQuery.getGmtModifiedEnd());
        }
        if (salaryBasicQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + salaryBasicQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example, salaryBasicQuery.getOrders());
        return example;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SalaryBasicVO saveSalaryBasic(SalaryBasicAddDTO salaryBasicAddDTO, TokenUser tokenUser) {
        // 根据员工ID和站点ID查询DO
        Example example = new Example(SalaryBasicDO.class);
        example.and()
                .andEqualTo("empId", salaryBasicAddDTO.getEmpId())
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        SalaryBasicDO salaryBasicDOTmp = salaryBasicDAO.selectOneByExample(example);

        // 转DO
        SalaryBasicDO salaryBasicDO = salaryBasicAddDTO.to(SalaryBasicDO.class);

        if (salaryBasicDOTmp == null) {
            // 保存
            salaryBasicDO = save(salaryBasicDO, tokenUser.getSiteId(), tokenUser.getUserId());
        } else {
            // 保存
            salaryBasicDO.setId(salaryBasicDOTmp.getId());
            updateByIdSelective(salaryBasicDO, tokenUser.getSiteId(), tokenUser.getUserId());
        }
        return salaryBasicDO.to(SalaryBasicVO.class);
    }

    @Override
    public Page<SalaryBasicVO> selectPageEmpSalary(SalaryBasicQuery salaryBasicQuery, String siteId) {
        PageInfo<SalaryBasicVO> pageInfo =
                PageHelper.startPage(salaryBasicQuery.getPageNo(), salaryBasicQuery.getPageSize()).doSelectPageInfo(() ->
                        salaryBasicDAO.selectEmpInfoByCompanyId(salaryBasicQuery, siteId));
        Page<SalaryBasicVO> empSocInfoListVoPage = new Page<>(pageInfo.getList(), pageInfo.getPageNum()
                , pageInfo.getPageSize(), (int) pageInfo.getTotal());
        return empSocInfoListVoPage.to(SalaryBasicVO.class);
    }

    @Override
    public List<SalaryBasicVO> selectEmpSalary(SalaryBasicQuery salaryBasicQuery, String siteId) {
        return salaryBasicDAO.selectEmpInfoByCompanyId(salaryBasicQuery, siteId);
    }

    @Override
    public List<SalaryBasicVO> selectByCompanyIdAndEmpIds(String companyId, List<String> empIds, String siteId) {
        if (CollectionUtils.isEmpty(empIds)) {
            return new ArrayList<>();
        }
        return salaryBasicDAO.selectByCompanyIdAndEmpIds(companyId, empIds, siteId);
    }

    @Override
    public SalaryBasicVO selectEmpSalary(String id, String siteId) {
        return salaryBasicDAO.selectEmpInfoByNumber(id, siteId);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer insertEmpSalary(SalaryBasicAddDTO salaryBasicAddDTO, TokenUser tokenUser) {
        SalaryBasicDO salaryBasicDO = new SalaryBasicDO();
        BeanUtils.copyProperties(salaryBasicAddDTO, salaryBasicDO);
        salaryBasicDO.preInsert(tokenUser.getUserId());
        salaryBasicDO.setId(UUID.randomUUID().toString().replace("-", ""));
        salaryBasicDO.setSiteId(tokenUser.getSiteId());
        //插入记录表
        SalaryChangesDO salaryChangesDO = new SalaryChangesDO();
        salaryChangesDO.setId(UUID.randomUUID().toString().replace("-", ""));
        salaryChangesDO.setEmpId(salaryBasicDO.getEmpId());
        salaryChangesDO.setEffectiveStatus(true);
        salaryChangesDO.setEffectiveDate(new Date());
        salaryChangesDO.setChangeReason(salaryBasicDO.getReason());
        salaryChangesDO.setSalaryNew(salaryBasicDO.getSalaryBasic());
        salaryChangesDO.setTrafficSubsidyNew(salaryBasicDO.getTrafficSubsidy());
        salaryChangesDO.setMealSubsidyNew(salaryBasicDO.getMealSubsidy());
        salaryChangesDO.setSalaryPerformanceNew(salaryBasicDO.getSalaryPerformance());
        salaryChangesDO.setSalaryTotalNew(salaryBasicDO.getSalaryTotal());
        salaryChangesDO.setRemark(salaryBasicDO.getRemark());
        salaryChangesDO.setCompanyId(salaryBasicDO.getCompanyId());
        salaryChangesDO.setSiteId(tokenUser.getSiteId());
        salaryChangesDO.preInsert(tokenUser.getUserId());
        salaryChangesDO.setChangeType(1);
        int changes = salaryChangesDAO.insert(salaryChangesDO);
        int basic = salaryBasicDAO.insert(salaryBasicDO);
        return basic;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer updateEmpSalary(SalaryBasicAddDTO salaryBasicAddDTO, TokenUser tokenUser) {
        SalaryBasicDO salaryBasicDO = new SalaryBasicDO();
        BeanUtils.copyProperties(salaryBasicAddDTO, salaryBasicDO);
        salaryBasicDO.preInsert(tokenUser.getUserId());
        salaryBasicDO.setId(UUID.randomUUID().toString().replace("-", ""));
        salaryBasicDO.setSiteId(tokenUser.getSiteId());
        //插入记录表
        SalaryChangesDO salaryChangesDO = new SalaryChangesDO();
        salaryChangesDO.setId(UUID.randomUUID().toString().replace("-", ""));
        salaryChangesDO.setEmpId(salaryBasicDO.getEmpId());
        salaryChangesDO.setEffectiveStatus(true);
        salaryChangesDO.setEffectiveDate(salaryBasicAddDTO.getEffectiveDate());
        salaryChangesDO.setChangeReason(salaryBasicDO.getReason());
        salaryChangesDO.setSalaryNew(salaryBasicDO.getSalaryBasic());
        salaryChangesDO.setTrafficSubsidyNew(salaryBasicDO.getTrafficSubsidy());
        salaryChangesDO.setMealSubsidyNew(salaryBasicDO.getMealSubsidy());
        salaryChangesDO.setSalaryPerformanceNew(salaryBasicDO.getSalaryPerformance());
        salaryChangesDO.setSalaryTotalNew(salaryBasicDO.getSalaryTotal());
        salaryChangesDO.setRemark(salaryBasicDO.getRemark());
        salaryChangesDO.setCompanyId(salaryBasicDO.getCompanyId());
        salaryChangesDO.setSiteId(tokenUser.getSiteId());
        salaryChangesDO.preInsert(tokenUser.getUserId());
        salaryChangesDO.setChangeType(2);
        int changes = salaryChangesDAO.insert(salaryChangesDO);
        int basic = salaryBasicDAO.updateSalaryBasic(salaryBasicAddDTO, tokenUser.getSiteId());
        return basic;
    }

    @Override
    public Page<SalaryChangesVO> selectPageChanges(SalaryChangesQuery salaryChangesQuery, String siteId) {
        PageInfo<SalaryChangesVO> pageInfo =
                PageHelper.startPage(salaryChangesQuery.getPageNo(), salaryChangesQuery.getPageSize()).doSelectPageInfo(() ->
                        salaryBasicDAO.selectChanges(salaryChangesQuery, siteId));
        Page<SalaryChangesVO> empSocInfoListVOPage = new Page<>(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), (int) pageInfo.getTotal());
        return empSocInfoListVOPage.to(SalaryChangesVO.class);
    }
}




